package com.auth.domain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.auth.control.model.RoleAuthDto;
import com.auth.domain.mapper.authmanage.RoleAuthMapper;
import com.auth.domain.module.po.authmanage.RoleAuth;
import com.auth.domain.module.vo.authmanage.AuthVO;
import com.auth.domain.service.IAuthService;
import com.auth.domain.service.IRoleAuthService;
import com.bean.ObjectMapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色权限表 服务实现类
 * </p>
 *
 * @author cyj
 * @since 2020-10-21
 */
@Service
public class RoleAuthServiceImpl extends ServiceImpl<RoleAuthMapper, RoleAuth> implements IRoleAuthService {

    @Autowired
    private IAuthService authService;

    @Override
    public boolean removeByRoleId(Long roleId) {
        return remove(new QueryWrapper<>(new RoleAuth().setRoleId(roleId)));
    }

    @Override
    public List<RoleAuth> getByRoleId(Long roleId) {
        return this.baseMapper.selectList(new QueryWrapper<>(new RoleAuth().setRoleId(roleId)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRoleAuths(Long roleId, List<RoleAuthDto> roleAuthDtos) {
        this.removeByRoleId(roleId);
        List<RoleAuth> roleAuths = ObjectMapperUtils.clones(roleAuthDtos, RoleAuth.class);
        this.saveBatch(roleAuths);
    }

    @Override
    public List<AuthVO> getRoleAuths(Long roleId) {
        LambdaQueryWrapper<RoleAuth> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(RoleAuth::getRoleId, roleId);
        List<RoleAuth> list = this.list(lambdaQueryWrapper);
        Set<Long> authIds = list.stream().map(RoleAuth::getAuthId).collect(Collectors.toSet());
        return authService.getByIds(authIds);
    }
}
